<?php
namespace App\GraphQL\Mutations\PriceSpecification;

use App\Models\PriceSpecification;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

class Update
{

    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $id = $args['id'];
        $data = $args['input'];
        $ad = $this->validate($id, $data);
        $data['price'] = intval($data['price']*100);
        // 更新广告
        $ad->update($data);
        return [
            'status' => '200',
            'message' => '更新成功'
        ];
    }

    public function validate($id, $data)
    {
        $cates = [
            'NORMAL',
            'PRIVATE'
        ];
        $styles = [
            'INTERNET_CAFE',
            'TEA_HOUSE'
        ];
        $rules = [
            'name' => [
                'required',
                'max:18'
            ],
            'cate' => [
                'required',
                Rule::in($cates)
            ],
            'style'=>[
                'required',
                Rule::in($styles)
            ],
            'duration'=>[
                'required',
                'numeric'
            ],
            'price' => [
                'required',
                'numeric',
            ]
        ];
        if($data['cate'] === 'PRIVATE') {
            $rules['province']=[
                'required'
            ];
        }
        $messages = [
            'name.required' => '名称不能为空',
            'name.max' => '名称不能超过18个字',
            'cate.required' => '分类不能为空',
            'cate.in' => '分类不能超出限制',
            'style.required' => '款式不能为空',
            'style.in' => '款式不能超出限制',
            'duration.required' => '时长不能为空',
            'duration.numeric' => '时长为数字',
            'price.required' => '价格不能为空',
            'price.numeric' => '价格为数字',
            'province.required'=>'地区不能为空'
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        $old = PriceSpecification::find($id);
        if (! $old) {
            throw new \Exception('价格设置不存在!');
        }
        return $old;
    }
}
